package com.cat.dataStructure;

import java.util.Arrays;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/search-a-2d-matrix-ii/description/?envType=study-plan-v2&envId=top-100-liked
 * @create 2025/9/25 21:15
 * @since JDK17
 */

public class Solution80 {
    boolean find(int[][] matrix, int c, int target) {
        int l = -1, r = matrix.length, mid;
        while (l + 1 < r) {
            mid = l + r >> 1;
            if (matrix[mid][c] > target) {
                r = mid;
            } else if (matrix[mid][c] < target) {
                l = mid;
            } else {
                return true;
            }
        }
        return false;
    }

    public boolean searchMatrix(int[][] matrix, int target) {
        int n = matrix.length, m = matrix[0].length;
        for (int[] row : matrix) {
            int r = Arrays.binarySearch(row, target);
            if (r > 0) {
                return true;
            }
            if (-r < row.length && find(matrix, -r, target)) {
                return true;
            }
        }

        return false;
    }
}
